<template>
    <div
      ref="sliderContainer"
      @mousemove="onMouseMove"
      @mouseup="onMouseUp"
      class="slider-verify-container"
      @mouseleave="onMouseLeave"
    >
      <span v-if="blockState === 0">请按住滑块，拖动到最右边获取验证码</span>
      <div
        @mousedown="onMouseDown"
        :style="{ left: leftP }"
        class="slider-verify-block"
        :class="{ 'success': blockState === 2 }"
      />
      <div :style="{ width: leftP }" class="slider-verify-complete">
        <span v-if="blockState === 2">验证成功</span>
      </div>
    </div>
  </template>
  <script setup>
  import { ref, defineEmits } from "vue";
  const emit = defineEmits(["success", "failed"]);
  const leftP = ref("0");
  const blockState = ref(0);
  const startP = ref(undefined);
  const sliderContainer = ref(undefined);
  const onMouseDown = (e) => {
    if (blockState.value !== 2) {
      leftP.value = "0";
      blockState.value = 1;
      startP.value = {
        clientX: e.clientX,
      };
    } else {
      leftP.value = "0";
      blockState.value = 0;
    }
  };
  const onMouseMove = (e) => {
    if (blockState.value === 1) {
      let width = e.clientX - startP.value.clientX;
      if (width + 56 > 400) {
        leftP.value = 400 - 80 + "px";
        blockState.value = 2;
        emit("success");
      } else {
        leftP.value = width + "px";
      }
    }
  };
  const onMouseUp = (e) => {
    if (blockState.value !== 2) {
      leftP.value = "0";
      blockState.value = 0;
      emit("failed");
    }
  };
  const onMouseLeave = (e) => {
    if (blockState.value !== 2) {
      leftP.value = "0";
      blockState.value = 0;
      emit("failed");
    }
  };
  </script>
  <style lang="scss" scoped>
  .slider-verify-container {
    width: 480px;
    height: 40px;
    background-color: transparent;
    position: relative;
    border: solid 1px #eee;
    text-align: center;
    color: rgba(0,0,0,0.65);
    background-color: #FAFAFA;
    line-height: 40px;
    user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -webkit-user-select: none;
  }
  .slider-verify-complete {
    width: 0;
    height: 40px;
    position: absolute;
    background-color: #4BC98C;
    color: #fff;
    left: 0;
    top: 0;
  }
  .slider-verify-block {
    width: 39px;
    height: 38px;
    background-image: url("@/assets/images/arrow.png");
    background-color: white;
    position: absolute;
    top:0px;
    background-color: #fff;
    background-size: 50%;
    background-repeat: no-repeat;
    background-position: center;
  }
  .success {
    top: 0px;
    width: 39px;
    height: 38px;
    background-image: url("@/assets/images/checkbox-circle-fill.png");
    background-color: white;
    border: 1px solid #4BC98C;
  }
  </style>